package com.yami.shop.distribution.api.controller;


import cn.hutool.json.JSONObject;
import com.yami.shop.bean.app.dto.ResourcesInfoDto;
import com.yami.shop.bean.enums.QRCodeType;
import com.yami.shop.bean.model.QrcodeTicket;
import com.yami.shop.common.bean.Domain;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.IdUtil;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.config.WxConfig;
import com.yami.shop.service.AttachFileService;
import com.yami.shop.service.QrcodeTicketService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Objects;

/**
 * @author LGH
 */
@Slf4j
@RestController
@RequestMapping("/p/distribution/qrCode")
@Tag(name="生成二维码接口")
public class DistributionQrCodeController {

    @Autowired
    private QrcodeTicketService qrcodeTicketService;
    @Autowired
    private WxConfig wxConfig;
    @Autowired
    private IdUtil idUtil;
    @Autowired
    private AttachFileService attachFileService;
    @Autowired
    private ShopConfig shopConfig;

    @GetMapping("/invitation")
    @Operation(summary ="分销员邀请二维码",description="分销员的邀请二维码带有cardNo")
    @Parameters({
            @Parameter(name = "scene", description = "二维码携带的参数", required = true),
            @Parameter(name = "page", description = "获取二维码后跳转的页面", required = true)
    })
    public ResponseEntity<FileSystemResource> qrCodeCreate(String page,String scene) throws WxErrorException {
        File file = wxConfig.getWxMaService().getQrcodeService().createWxaCodeUnlimit(scene, page);
        return ResponseEntity.ok().contentLength(file.length()).contentType(MediaType.IMAGE_PNG).body(new FileSystemResource(file));
    }

    @GetMapping("/invitationPath")
    @Operation(summary = "分销商品推广二维码" , description = "分销员商品推广二维码")
    @Parameters({
            @Parameter(name = "content", description = "要保存的内容", required = true),
            @Parameter(name = "type", description = "类型：1. 小程序团购商品 2.小程序分销商品二维码", required = true)
    })
    public ServerResponseEntity<ResourcesInfoDto> qrCodeCreatePath(String content, Integer type) throws WxErrorException {
        String page;
        if(Objects.equals(type, QRCodeType.GROUP.value()) || Objects.equals(type, QRCodeType.DISTRIBUTION.value())) {
            page = "pages/prod/prod";
        }else if(Objects.equals(type, 3))  {
            page = "pages/snapUpDetail/snapUpDetail";
        } else {
            // 无法获取页面信息
            throw new YamiShopBindException("yami.unable.get.page");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("type", type);
        jsonObject.set("content", content);

        String ticket = idUtil.nextShortId();
        QrcodeTicket qrcodeTicket = new QrcodeTicket();
        qrcodeTicket.setContent(jsonObject.toString());
        qrcodeTicket.setCreateTime(new Date());
        qrcodeTicket.setType(type);
        qrcodeTicket.setTicket(ticket);
        qrcodeTicket.setTicketUrl(page);
        qrcodeTicketService.save(qrcodeTicket);
        File file = wxConfig.getWxMaService().getQrcodeService().createWxaCodeUnlimit(ticket, page);
        ResourcesInfoDto resourcesInfoDto = null;
        //新的 byte 数组输出流，缓冲区容量1024byte
        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);){
            //缓存
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            //改变为byte[]
            byte[] data = bos.toByteArray();
            //
            String fileName = attachFileService.uploadFile(data,file.getName());
            Domain domain = shopConfig.getDomain();
            String resourcesUrl = domain.getResourcesDomainName();

            resourcesInfoDto = new ResourcesInfoDto();
            resourcesInfoDto.setResourcesUrl(resourcesUrl);
            resourcesInfoDto.setFilePath(fileName);
            return ServerResponseEntity.success(resourcesInfoDto);
        } catch (Exception e) {
            log.error("获取分销员邀请二维码错误:", e);
        }
        return ServerResponseEntity.success();
    }
}
